package com.cwd.controller;

import com.cwd.constant.MessageConstant;
import com.cwd.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @PackageName: com.cwd.controller
 * @ClassName: UserController
 * @Author: CWD
 * @Date: 2020/3/13 18:51
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当spring security完成认证之后，会将当前用户信息保存到框架提供的上下文环境
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
}
